import logging
import os

import requests
from websocket import WebSocketApp

from model.WebsocketClientVO import WebsocketClientVO
from service.UploadDataService import UploadDataService


class ClashService(object):

    def __init__(self, info: WebsocketClientVO):
        self.info = info
        self.__url = info.clashHost
        self.__configPath = info.clashPath
        self.uploadDataService = UploadDataService(info)

    def fetch(self, ws: WebSocketApp, url):
        try:
            res = requests.get(url)
            if res.status_code != 200:
                return False
            if not res.text:
                return False
            pd = os.path.dirname(self.__configPath)
            if not os.path.exists(pd):
                os.makedirs(pd)
            file = open(self.__configPath, 'w')
            file.write(res.next)
            response = requests.put(self.__url + 'configs')
            return response.status_code == 200
        except Exception as e:
            logging.exception(e)
            return False

    def getCurrentProxy(self, ws:WebSocketApp, data):
        return self.getCurrentProxyFormClash()

    def getCurrentProxyFormClash(self):
        data = requests.get(self.__url + 'proxies', headers={'Authorization': 'Bearer {}'.format(self.info.clashToken)}).json()
        try:
            name = data['proxies']['Proxy']['now']
            node = data['proxies'][name]
            if node['history']:
                delay = node['history'][0]['delay']
            else:
                delay = 0
            return {
                'proxy_id': name,
                'delay': delay,
                'device_id': self.info.clientInfo
            }
        except Exception as e:
            print(e)

    def changeCurrentProxy(self, proxInfo):
        try:
            response = requests.get(self.__url + '/proxies')
            proxies = response.json()['proxies']
            # 找到要更新的代理接口名称
            update_proxy_name = 'proxy_name'
            update_proxy_info = [proxy for proxy in proxies if proxy['name'] == update_proxy_name][0]
            # 更新代理接口的信息
            update_proxy_info['server'] = proxInfo['server']
            update_proxy_info['port'] = proxInfo['port']
            update_proxy_info['password'] = proxInfo['port']
            # 发送 HTTP 请求更新代理接口的信息
            update_proxy_url = f'{self.__url}/proxies/{update_proxy_name}'
            response = requests.put(update_proxy_url, json=update_proxy_info)
            print(response.status_code)
        except Exception as e:
            logging.error(e)
            return False
        return True